package com.datasecops.scannerservices.watermark;

import com.alibaba.druid.pool.DruidDataSource;
import com.datasecops.scannerservices.configurationfiles.WatermarkingConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.*;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;


/**数据库水印配置文件的生成
 * @author: GeXiaoLong
 * @time: 2023/1/5 17:53
 */
@Service
@Slf4j
public class MysqlDBCS {
    public static Map<String, DruidDataSource> dataSourceMap = new HashMap<>();

    public  void watermarkingDatabase() throws SQLException {
        log.error("数据库安装程序进来了吗?");
        Statement st = null;
        try {
            log.error("数据库安装程序运行进来了吗?");
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://10.26.18.58:3306/mysql?useUnicode=true&characterEncoding=UTF8&useSSL=false&serverTimezone=Asia/Shanghai";
            String username = "root";
            String password = "Wzx.1104";
            Connection c = DriverManager.getConnection(url, username, password);
            st = c.createStatement();
            //int i = st.executeUpdate("create table test(id int,name varchar (80))");
            //rs = st.executeQuery("select * from student");

//            st.executeUpdate("create schema WatermarkingDatabase");//创建数据库
            st.executeUpdate("CREATE DATABASE IF NOT EXISTS WatermarkingDatabase");//创建数据库,有就跳过,没有就创建

        } catch (Exception e) {
            log.error("数据库添加程序运行失败,原因是: ",e);
        } finally {
            st.close();
        }
//        String url = "jdbc:mysql://10.26.18.58:3306";
//        String properties = "useUnicode=true;characterEncoding=UTF8;useSSL=false;serverTimezone=Asia/Shanghai";
//        Properties prop = getCommonProp("root", "Wzx.1104", DBDrive.MYSQL.getValue(), url, properties);
//        try {
//            DruidDataSource druidDataSource = (DruidDataSource) DruidDataSourceFactory
//                    .createDataSource(prop);
//            putSourceMap(getSourceMapKey("10.26.18.58", 3306), druidDataSource);
//            String sourceMapKey = getSourceMapKey("10.26.18.58", 3306);
//            Connection connection = getConnection(sourceMapKey);
//            st = connection.createStatement();
//            st.executeUpdate("create schema WatermarkingDatabase");//创建数据库
//        } catch (Exception e) {
//            e.printStackTrace();
//            System.out.println("初始化创建连接池失败！");
//        }

    }
//    /**
//     * putMap
//     *
//     * @param
//     * @return
//     * @Description
//     * @author SunLingzhi
//     * @time 2022/8/15 11:23
//     */
//    public static void putSourceMap(String sourceMapKey, DruidDataSource druidDataSource) {
//        dataSourceMap.put(sourceMapKey, druidDataSource);
//    }
//
//    /**
//     * 获取连接
//     *
//     * @param
//     * @return
//     * @Description
//     * @author SunLingzhi
//     * @time 2022/8/15 11:37
//     */
//    public static Connection getConnection(String key) {
//        Connection conn = null;
//        try {
//            DruidDataSource source = dataSourceMap.get(key);
//            conn = source.getConnection();
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
//        return conn;
//    }
//
//    /**
//     * 获取sourceMap的key
//     *
//     * @param
//     * @return
//     * @Description
//     * @author SunLingzhi
//     * @time 2022/8/12 19:28
//     */
//    public static String getSourceMapKey(String ip, int port) {
//        return ip + "_" + port;
//    }
//

    public  void completeWatermarking(WatermarkingConfiguration watermarkingConfiguration) throws SQLException {
        Statement st = null;
        try {
            log.error("数据库安装程序运行进来了吗2?");
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://" +watermarkingConfiguration.getHOST()+":"+watermarkingConfiguration.getPORT()+"/mysql?useUnicode=true&characterEncoding=UTF8&useSSL=false&serverTimezone=Asia/Shanghai";
            String username = watermarkingConfiguration.getUSER();
            String password = watermarkingConfiguration.getPASSWORD();
            Connection c = DriverManager.getConnection(url, username, password);
            st = c.createStatement();
            //int i = st.executeUpdate("create table test(id int,name varchar (80))");
            //rs = st.executeQuery("select * from student");
            st.executeUpdate("CREATE DATABASE IF NOT EXISTS WatermarkingDatabase");//创建数据库
//            System.out.println(c);
//            ResultSetMetaData metaData = rs.getMetaData();
//            int columeCount=metaData.getColumnCount();
//            String columnName = metaData.getColumnName(1);
//            int columnType = metaData.getColumnType(1);
//            String columnTypeName = metaData.getColumnTypeName(1);
//            int columnDisplaySize = metaData.getColumnDisplaySize(1);
//
//            while(rs.next()){
//                String s = rs.toString();
//                System.out.println(s);
////                System.out.println(rs.getString("ID")
////                        + rs.getString(2) + rs.getString("Module"));
//
//                System.out.println(rs.getObject(1)+"\t"+rs.getObject(2));
//            }
//
//            c.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            log.error("数据库添加程序运行失败,原因是:    "+e.getMessage());
        } finally {
            st.close();
        }

    }
//    //获取生成水印配置文件
//    public  void diskDropFile(WatermarkingConfiguration ss) throws IOException {
//        File outFile = new File("/root/watermark/dso_dbwm/WmCfg.txt");
//        boolean exists = outFile.exists();
//        if (exists){
//            outFile.delete();
//        }else {
//            outFile.createNewFile();
//        }
//
//        Writer out ;
//        String host = ss.getHost();
//        String port = ss.getPort();
//        String user = ss.getUser();
//        String password = ss.getPassword();
//        String dbName = ss.getDbName();
//        String embedTableName = ss.getEmbedTableName();
//        String embedWmFileName = ss.getEmbedWmFileName();
//        String embedAuxInfoFileName = ss.getEmbedAuxInfoFileName();
//        String runOutFileName = ss.getRunOutFileName();
//        String tableDesFileName = ss.getTableDesFileName();
//        String wmType = ss.getWmType();
//        String operType = ss.getOperType();
//        String traceWmEmbedChars = ss.getTraceWmEmbedChars();
//        String characterSet = ss.getCharacterSet();
//        String dbLoaded = ss.getDbLoaded();
//        String reUseTableInfo = ss.getReUseTableInfo();
//        String splitChars = ss.getSplitChars();
//        String splitLineChars = ss.getSplitLineChars();
//        String enclosedChars = ss.getEnclosedChars();
//        String mysqlClientSo = ss.getMysqlClientSo();
//        String fakeRowEmbedProp = ss.getFakeRowEmbedProp();
//        String distortThreshold = ss.getDistortThreshold();
//        try {
//            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile,true),"utf-8"),10240);
//            InFile(out, host, port, user, password, dbName, embedTableName, embedWmFileName, embedAuxInfoFileName,
//                    runOutFileName, tableDesFileName, wmType);
//            InFile(out, operType, traceWmEmbedChars, characterSet, dbLoaded, reUseTableInfo, splitChars, splitLineChars, enclosedChars, mysqlClientSo, fakeRowEmbedProp, distortThreshold);
//            out.flush();
//            out.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    private static void InFile(Writer out, String host, String port, String user, String password, String dbName,
//                               String embedTableName, String embedWmFileName, String embedAuxInfoFileName,
//                               String runOutFileName, String tableDesFileName, String wmType) throws IOException {
//        Infiles(out, host, port, user, password, dbName);
//        Infiles(out, embedTableName, embedWmFileName, embedAuxInfoFileName, runOutFileName, tableDesFileName);
//        out.write(wmType);
//        out.write("\n");
//    }
//
//    public static void Infiles(Writer out, String host, String port, String user, String password, String dbName) throws IOException {
//        out.write(host);
//        out.write("\n");
//        out.write(port);
//        out.write("\n");
//        out.write(user);
//        out.write("\n");
//        out.write(password);
//        out.write("\n");
//        out.write(dbName);
//        out.write("\n");
//    }

    public static void main(String[] args) throws SQLException, IOException {
        //watermarkingDatabase();
        WatermarkingConfiguration ss = new WatermarkingConfiguration();
        String DbName = "soul";
        String OperType = "OtEmbed";
        String EmbedRableNAme = "student";
        String WmType = "WmFakeRow,WmDigitalAsb,WmDigitalHsw";
        String TraceWmEmbedChars = "DSO Database IPR, 2022.11.11, China Beijing. To:China Mobile. Usage:Collaboration, Validity:2200.12.31.";
        String dbName = ss.getDbName()+DbName;
        ss.setDbName(dbName);
        String operType = ss.getOperType()+OperType;
        ss.setOperType(operType);
        if ("OtEmbed".equalsIgnoreCase(OperType)){
            String embedTableName = ss.getEmbedTableName()+EmbedRableNAme;
            ss.setEmbedTableName(embedTableName);
            String extractWmFileNameName = ss.getEmbedWmFileName()+EmbedRableNAme+".txt";
            ss.setEmbedWmFileName(extractWmFileNameName);
            String extractAuxInfoFileName = ss.getEmbedAuxInfoFileName()+EmbedRableNAme+".txt";
            ss.setEmbedAuxInfoFileName(extractAuxInfoFileName);
        }
        String runOutFileName = ss.getRunOutFileName()+EmbedRableNAme+".log";
        ss.setRunOutFileName(runOutFileName);
        String tableDesFileName = ss.getTableDesFileName()+EmbedRableNAme+".txt";
        ss.setTableDesFileName(tableDesFileName);
        String wmType = ss.getWmType()+WmType;
        ss.setWmType(wmType);
        String traceWmEmbedChars = ss.getTraceWmEmbedChars()+TraceWmEmbedChars;
        ss.setTraceWmEmbedChars(traceWmEmbedChars);
        //diskDropFile(ss);

    }


}

